package com.hqy.hb.tools;

import com.google.common.base.Splitter;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.StringUtils;
import org.yaml.snakeyaml.Yaml;
import java.io.InputStream;
import java.util.List;
import java.util.Map;


public class YamlUtil {

    private static Map<String, Object>  kvMap;

    static {

        Yaml yaml = new Yaml();
        // yaml文件路径
        InputStream in = Yaml.class.getClassLoader().getResourceAsStream("app.yaml");
        kvMap = yaml.loadAs(in, Map.class);
    }



    /**
     * @param key: 完整的key值, 多层级key之间用"."拼接
     * @return
     */
    public static Object getValue(String key){

        if(StringUtils.isBlank(key)){
            return null;
        }
        List<String> subKeys = Splitter.on(".").omitEmptyStrings().trimResults().splitToList(key);
        if(subKeys.size() == 1){
            return  kvMap.get(key);
        }
        if(subKeys.size() == 2){
            return ((Map<String,Object>)kvMap.get(subKeys.get(0))).get(subKeys.get(1));
        }
        Map<String, Object> subKvMap = (Map<String,Object>)kvMap.get(subKeys.get(0));
        for (int index = 1; index <= subKeys.size() - 2; index ++){
            subKvMap = (Map<String, Object>)subKvMap.get(subKeys.get(index));
        }
        return subKvMap.get(subKeys.get(subKeys.size() - 1));
    }

}
